package com.example;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisRawDemo {
    public static void main(String[] args) throws IOException {
        InputStream in = null;
        try  {
            // 1. 加载配置文件
            String resource = "mybatis-config.xml";
            in = Resources.getResourceAsStream(resource);
            // 2. 构建 SqlSessionFactory
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
            SqlSession session = sqlSessionFactory.openSession(false);

            // ---------- 自动建表 ----------
            session.update("com.example.mapper.UserMapper.createTable");
            session.commit();   // DDL 也要提交
            // ------------------------------

            // 4. 获取 Mapper 代理对象
            UserMapper mapper = session.getMapper(UserMapper.class);
            User u = new User();
            u.setName("alice");
            u.setAge(18);
            mapper.insert(u);
            System.out.println("insert -> id=" + u.getId());

            // 8. 提交事务
            session.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            in.close();
        }
    }
}
